<?php
namespace Home\Controller;
use Home\Controller\BaseController;
class UserController extends BaseController{
    private  $appid='';
    private  $appsecret='';
    public function _initialize(){
        $this->appid='wx1c4dbd90c2e49ac3';
        $this->appsecret='7d9eee8a999f16d409d2fd7386f681a7';
    }
    //微信服务器的验证
    public function index(){
        $this->checkSignnature();
    }
    /**
     * 获取微信服务器验证
     * @param string '';
     */
    public function checkSignnature(){
        $signature = isset($_GET["signature"])?$_GET["signature"]:'';
        $signature = isset($_GET["msg_signature"])?$_GET["msg_signature"]:$signature; //如果存在加密验证则用加密验证段
        $timestamp = isset($_GET["timestamp"])?$_GET["timestamp"]:'';
        $nonce = isset($_GET["nonce"])?$_GET["nonce"]:'';
        $echostr=isset($_GET['echostr'])?$_GET['echostr']:'';
        
        $token='sumjoin';
        $tmpArr=array($timestamp,$nonce,$token);
        sort($tmpArr,SORT_STRING);
        $tmpstr=implode($tmpArr);
        $tmpstr=sha1($tmpstr);
        
        if($tmpstr==$signature){
            echo $echostr;
            return ;
        }else{
            return false;
        }
    }
    /**
     * 获取全局授权token
     *
     * @param string $access_token;
     */
    public function getAccesstoken(){
       if(S('access_token')===false){
            $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appid}&secret={$this->appsecret}";
            $access_token=json_decode($this->http_get($url),true);
            S('access_token',$access_token['access_token'],$access_token['expires_in']); 
            $access_token=S('access_token');
       }else{
            $access_token=S('access_token');
       }
       return $access_token;
    }
    /**
     * oauth 授权跳转接口
     * @param string $callback 回调URI
     * @return string
     */
    public function getOuthCode(){
        $redirect_uri="http://www.gaoshengyiyi.cn/index.php/Home/User/getOuthUserinfo";
        $url="https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->appid}&redirect_uri=".urlencode($redirect_uri)."&response_type=code&scope=snsapi_base&state=jianye#wechat_redirect ";
        header('location:'.$url);
    }
    /**
     * 通过code获取网页授权Access Token
     * @return array {access_token,expires_in,refresh_token,openid,scope}
     */
    public function getOuthToken(){
        $code = isset($_GET['code'])?$_GET['code']:'';
        if(!$code)exit;
        $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->appid}&secret={$this->appsecret}&code={$code}&grant_type=authorization_code ";
        $json=json_decode($this->http_get($url),true);
        return $json;
    }
    /**
     * 刷新access token并续期
     */
    public function getOuthRreshToken(){
        $url="https://api.weixin.qq.com/sns/oauth2/refresh_token?appid={$this->appid}&grant_type=refresh_token&refresh_token={$this->getOuthToken()['refresh_token']} ";
        $result=$this->http_get($url);
        if($result){
            $json=json_decode($result,true);
            return $json; 
        }
        return false;
    }
    /**
     * 拉取用户数据
     */
    public function getOuthUserinfo(){
        $outh=$this->getOuthToken();
        $url="https://api.weixin.qq.com/sns/userinfo?access_token={$outh['access_token']}&openid={$outh['openid']}&lang=zh_CN ";  
        $userinfo=json_decode($this->http_get($url),true);
        if($userinfo){
            $data['openid']=$userinfo['openid'];
            $data['nickname']=$userinfo['nickname'];
            $data['addtime']=date("Y-m-d H:i:s",time());
            $res=M('user')->add($data);
            if($res){
                $this->redirect("Index/index");
            }
        }
        
    }
    public function test(){
      //dump(S('access_token'));
     // dump($this->getOuthCode());
        $res=M('user')->select();
        
        dump($res);
    }
    /**
     * Curl工具
     *
     * @param get请求
     */
    private function http_get($url){
        $ch=curl_init();
        //如果不是https协议
        if(stripos($url, "https://")!==false){
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($ch, CURLOPT_SSLVERSION, 1);//CURL_SSLVERSION_TLSv1 (1)
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $sContent=curl_exec($ch);
        $aStatus = curl_getinfo($ch);
        curl_close($ch);
        if(intval($aStatus["http_code"])==200){
            return $sContent;
        }else{
            return false;
        }
        
    }
     private function http_post($url,$param){
            $ch = curl_init();
            if(stripos($url,"https://")!==FALSE){
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
                curl_setopt($ch, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
            }
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
            curl_setopt($ch, CURLOPT_POST,true);
            curl_setopt($ch, CURLOPT_POSTFIELDS,$param);
            $sContent = curl_exec($ch);
            $aStatus = curl_getinfo($ch);
            curl_close($ch);
            if(intval($aStatus["http_code"])==200){
                return $sContent;
            }else{
                return false;
            }
        }
    
}